# encoding: utf-8

from django.http import HttpResponse
from wxxiaohello.models import Blog,Classify,Tag,Comment, Filing
from django.template import loader,Context
from django.shortcuts import render_to_response,RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login as user_login, logout as user_logout
from django.http import  HttpResponseRedirect
from  datetime  import  date  
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.core.paginator import PageNotAnInteger
from django.core.paginator import EmptyPage
from django.shortcuts import render
from wxxiaohello import jsondump
from django.db import connection,transaction
import os
# Create your views here.

# page for index.html and default.html
def index(request):
    # define how many blogs in a blog list page
    pn = request.GET.get('pn')
    if pn is None:
        pn=1;
    pn = int(pn)
    
    blogs = Blog.objects.filter(release=1).order_by("-id")
    paginator  = Paginator(blogs,10)
    try:
        blog_list = paginator.page(pn)
    except PageNotAnInteger:
        blog_list = paginator.page(1)
    except EmptyPage:
        blog_list = paginator.page(paginator.num_pages)
     
    for blog in blog_list:
        blog.tags = blog.tag.all()

 

    context = Context({
                       "blog_list":blog_list,
                       "query":"/?h=",
                       "title":"首页",
                       })

    return render(request, "index.html", context)

# page for detail blog content
def blog(request,blog_id):
    
    try:
        blog = Blog.objects.get(id = blog_id)
        blog.tags = blog.tag.all()

        try:
            nextBlog = Blog.objects.filter(id__gt = blog_id).filter(release=1).order_by("id")[0]
        except:
            nextBlog = None
        try:
            preBlog = Blog.objects.filter(id__lt = blog_id).filter(release=1).order_by("-id")[0]
        except:
            preBlog = None
        blog.preBlog= preBlog
        blog.nextBlog = nextBlog
        
        comments = Comment.objects.filter(blog_id=blog_id).order_by("-id")
        blog.comments = comments
    except:
        ##
        blog = None
        
    context = Context({
                       "blog":blog,
                       })
  
    return render(request, "blog.html", context)

###根据  tag_id查询 文章
def tag_blog(request,tag_id):
    tagcontent="none"
    try:
        tag = Tag.objects.get(id=tag_id)
        pn = request.GET.get('pn')
        if pn is None:
            pn=1;
        pn = int(pn)
        
        blogs = tag.blog_set.all().order_by("-id")
        paginator  = Paginator(blogs,10)
        try:
            blog_list = paginator.page(pn)
        except PageNotAnInteger:
            blog_list = paginator.page(1)
        except EmptyPage:
            blog_list = paginator.page(paginator.num_pages)
            
        for blog in blog_list:
            blog.tags = blog.tag.all()
        tagcontent = tag.content
    except:
        blog_list=None

    context = Context({
                       "blog_list":blog_list,
                       "query":"/tag/"+str(tag_id)+"/?h=",
                       "title":"标签-"+str(tagcontent.encode("utf-8")),
                       })
    
    return render(request, "index.html", context)


###根据 分组id  classify_id查询 文章
def group_blog(request,classify_id):
    pn = request.GET.get('pn')
    if pn is None:
        pn=1;
    pn = int(pn)
    
    blogs = Blog.objects.filter(classify_id= classify_id).order_by("-id")
    paginator  = Paginator(blogs,10)
    try:
        blog_list = paginator.page(pn)
    except PageNotAnInteger:
        blog_list = paginator.page(1)
    except EmptyPage:
        blog_list = paginator.page(paginator.num_pages)
        
    for blog in blog_list:
        blog.tags = blog.tag.all()
    ###分组
    classifycontent = "none"
    try:
        classify = Classify.objects.get(id=classify_id)
        classifycontent =classify.content
    except:
        classifycontent = "none"

    context = Context({
                       "blog_list":blog_list,
                       "query":"/group/"+str(classify_id)+"/?h=",
                       "title":"分类-"+str(classifycontent.encode("utf-8")),
                       })
    
    return render(request, "index.html", context)
##文章查找
@csrf_exempt
def search(request):
    keyword = request.GET.get('keyword')
    pn = request.GET.get('pn')
    if pn is None:
        pn=1;
    pn = int(pn)
    
    blogs = Blog.objects.filter(title__contains=keyword.strip()).order_by("-id")
    paginator  = Paginator(blogs,10)
    try:
        blog_list = paginator.page(pn)
    except PageNotAnInteger:
        blog_list = paginator.page(1)
    except EmptyPage:
        blog_list = paginator.page(paginator.num_pages)
    
    
    for blog in blog_list:
        blog.tags = blog.tag.all()

    context = Context({
                       "blog_list":blog_list,
                       "query":"/search/?keyword="+keyword,
                       "title":"搜索-"+keyword.encode("utf-8"),
                       })
    
    return render(request, "index.html", context)

@csrf_exempt
def login(request):
    #表单提交过来的数据
    redirect_to="/edit"
    
    if request.user.is_authenticated():
        return  HttpResponseRedirect(redirect_to) 
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                        user_login(request, user)
                        return HttpResponseRedirect(redirect_to) 
            else:
                    return render_to_response("login.html",{"message":"用户没有启用！"},context_instance=RequestContext(request))
        else:
                return render_to_response("login.html",{"message":"账号或密码错误！"},context_instance=RequestContext(request))
    else:
        return render_to_response('login.html')
    
def logout(request):
    user_logout(request)
    return HttpResponseRedirect('/index.html')

@login_required
def  create_new_blog(request):

    classifys = Classify.objects.all();

    return render_to_response("edit/create_new_blog.html",{"active":"create_new_blog","classifys":classifys}) 
##保存第一次（新建）的文章和草稿 create
@login_required
@csrf_exempt
def save_new_blog(request):
    user = request.user
    title = request.POST['title']
    summary = request.POST['summary']
    content = request.POST['content']
    tags = request.POST['tags']
    classify_id = request.POST['classify_id']
    rtype = request.POST['type']
    release = request.POST['release']
    
    blog = Blog.objects.create(user_id = user.id,title=title,summary = summary,content = content,type=rtype,release=release,time=date.today(),classify_id=classify_id)
    blog.save()
    ## 处理关键字 tag
    tags = " ".join(tags.split())
    if tags!=" " and len(tags)>0:  
        tags = tags.lstrip().rstrip().split(" ")
        for tc in tags:
            try:
                #已经存在的tag
                tag = Tag.objects.get(content=tc)
                blog.tag.add(tag)
            except:
                #新建立tag
                tag = Tag.objects.create(content=tc)
                tag.save()
                blog.tag.add(tag)
    
    return HttpResponse("success")


##获取草稿或者文章内容 get
@login_required
def get_edit_blog(request,blog_id):
    blog = Blog.objects.get(id = blog_id)
    tags = blog.tag.all()
    classifys = Classify.objects.all();
    active = "get_edit_blog_r"
    if blog.release==0:
        active = "get_edit_blog_d"
    context = Context({
                       "blog":blog,
                       "tags":tags,
                       "classifys":classifys,
                       "active":active,
                       })
    template  = loader.get_template("edit/get_edit_blog.html")
    return HttpResponse(template.render(context))

##修改 草稿，或者文章内容 update 
@csrf_exempt
@login_required
def save_update_blog(request):
    rid = request.POST["id"]
    title = request.POST['title']
    summary = request.POST['summary']
    content = request.POST['content']
    tags = request.POST['tags']
    classify_id = request.POST['classify_id']
    rtype = request.POST['type']
    release = request.POST['release']
    
    blog = Blog.objects.get(id=rid)
    blog.title = title
    blog.summary = summary
    blog.content = content
    blog.type = rtype
    blog.release = release
    blog.classify_id = classify_id
    
    if(blog.release ==0 and release==1):
        blog.time=date.today()
    blog.save()
    
    ### 处理 Tag, 去除原有的tag
    blog.tag.remove()
    
    ## 处理关键字 tag
    tags = " ".join(tags.split())
    if tags!=" " and len(tags)>0:  
        tags = tags.lstrip().rstrip().split(" ")
        for tc in tags:
            try:
                #已经存在的tag
                tag = Tag.objects.get(content=tc)
                blog.tag.add(tag)
            except:
                #新建立tag
                tag = Tag.objects.create(content=tc)
                tag.save()
                blog.tag.add(tag)
    return HttpResponse("success")

###获取已发布文章列表
@csrf_exempt
@login_required
def get_released_blog_list(request):
        
    pn = request.GET.get('pn')
    if pn is None:
        pn=1;
    pn = int(pn)
    
    blogs = Blog.objects.filter(release=1).order_by("-id")
    paginator  = Paginator(blogs,10)
    try:
        blog_list = paginator.page(pn)
    except PageNotAnInteger:
        blog_list = paginator.page(1)
    except EmptyPage:
        blog_list = paginator.page(paginator.num_pages)
     
    context = Context({
                       "blog_list":blog_list,
                       "active":"get_released_blog_list",
                       "query":"/edit/get_released_blog_list/?h=",
                       })
    
    template  = loader.get_template("edit/get_released_blog_list.html")
    return HttpResponse(template.render(context))

###获取草稿文章列表
@login_required
def get_draft_blog_list(request):
    pn = request.GET.get('pn')
    if pn is None:
        pn=1;
    pn = int(pn)
    
    blogs = Blog.objects.filter(release=0).order_by("-id")
    paginator  = Paginator(blogs,10)
    try:
        blog_list = paginator.page(pn)
    except PageNotAnInteger:
        blog_list = paginator.page(1)
    except EmptyPage:
        blog_list = paginator.page(paginator.num_pages)
        
   
    context = Context({
                       "blog_list":blog_list,
                       "active":"get_draft_blog_list",
                       "query":"/edit/get_draft_blog_list/?h=",
                       })
    
    template  = loader.get_template("edit/get_draft_blog_list.html")
    return HttpResponse(template.render(context))

@csrf_exempt
@login_required
def delete_blog(request):
    rid = request.POST["id"]
    blog = Blog.objects.get(id=rid)
    blog.tag.remove()
    blog.delete()
    return HttpResponse("success")
 
@csrf_exempt
@login_required
def get_classify_list(request):

    classify_list = Classify.objects.all()
    context = Context({
                       "classify_list":classify_list,
                       "active":"get_classify_list",
                       })
    
    template  = loader.get_template("edit/get_classify_list.html")
    return HttpResponse(template.render(context))

@csrf_exempt
@login_required
def delete_classify(request):
    rid = request.POST["id"]
    classify = Classify.objects.get(id=rid)
    blogs = Blog.objects.filter(classify_id=rid)
    if len(blogs) >0:
        for blog in blogs:
            blog.classify_id = 1
            blog.save()
    if(rid>1):
        classify.delete()
    return HttpResponse("success")

@csrf_exempt
@login_required
def add_classify(request):

    content = request.POST["content"]
    classify = Classify.objects.create()
    classify.content = content
    
    classify.save()
    return HttpResponse("success")

@csrf_exempt
@login_required
def update_classify(request):
    
    rid = request.POST["id"]
    content = request.POST["content"]
    classify = Classify.objects.get(id=rid)
    classify.content = content
    
    classify.save()
    return HttpResponse("success")


@csrf_exempt
def add_message(request):
    blog_id = request.POST["blog_id"]
    name = request.POST["name"]
    website = request.POST["website"]
                                         
    message = request.POST["message"]
    time = date.today()
    
    comment = Comment.objects.create()

    comment.blog_id=blog_id
    comment.name = name
    if(website and "http://" in website):
        comment.website = website
    comment.message = message
    comment.time = time
    comment.save()
    return HttpResponse("success")


@csrf_exempt
@login_required
def get_message_list(request):

    pn = request.GET.get('pn')
    if pn is None:
        pn=1;
    pn = int(pn)
    comments = Comment.objects.all().order_by("-id")
    paginator  = Paginator(comments,10)
    try:
        comment_list = paginator.page(pn)
    except PageNotAnInteger:
        comment_list = paginator.page(1)
    except EmptyPage:
        comment_list = paginator.page(paginator.num_pages)
        
    context = Context({
                       "comment_list":comment_list,
                       "active":"get_message_list",
                       "query":"/edit/get_message_list/?h=",
                       })
    
    template  = loader.get_template("edit/get_message_list.html")
    return HttpResponse(template.render(context))
    

@csrf_exempt
@login_required
def delete_message(request):
    rid = request.POST["id"]
    comment = Comment.objects.get(id=rid)
    comment.delete()
    return HttpResponse("success")
    
def NF404_viewer(requests):
    return render_to_response('404.html')

def NF500_viewer(requests):
    return render_to_response('404.html')

## 显示归档列表
@csrf_exempt
def filing_list(requests):
      
    if 'SERVER_SOFTWARE' in os.environ: ### if sae 
        cursor = connection.cursor()            #获得一个游标(cursor)对象
        raw_sql = "SELECT  DATE_FORMAT(wxxiaohello_blog.time, '%%Y-%%m') AS month,COUNT(wxxiaohello_blog.id) AS count FROM wxxiaohello_blog GROUP BY month ORDER BY month DESC"
        cursor.execute(raw_sql)
        fetchall = cursor.fetchall()    
        card=[]
        for obj in fetchall:
            dic={}
            dic['month']=str(obj[0])
            dic['count']=str(obj[1])
            card.append(dic)
      #  return HttpResponse(jsondump.json_encode(filing_list.values()))
        return HttpResponse(jsondump.json_encode(card))
    else:  ## if local
        filing_list = Filing.objects.all();
        return HttpResponse(jsondump.json_encode(filing_list.values()))

## 查询归档 月份下的文章
@csrf_exempt
def filing(request,year,month):
    try:
        pn = request.GET.get('pn')
        if pn is None:
            pn=1;
        pn = int(pn)
        
        blogs = Blog.objects.filter(time__year=year).filter(time__month=month).order_by("-id")
        paginator  = Paginator(blogs,10)
        try:
            blog_list = paginator.page(pn)
        except PageNotAnInteger:
            blog_list = paginator.page(1)
        except EmptyPage:
            blog_list = paginator.page(paginator.num_pages)
            
        for blog in blog_list:
            blog.tags = blog.tag.all()
    except:
        blog_list=None


    context = Context({
                       "blog_list":blog_list,
                       "query":"/filing/"+str(year)+"/"+str(month)+"/?h=",
                       "title":"归档-"+str(year)+"/"+str(month),
                       })
    
    return render(request, "index.html", context)


###查询分类文章数目
@csrf_exempt
def group_list(request):
        
        cursor = connection.cursor()            #获得一个游标(cursor)对象
        raw_sql = "SELECT wxxiaohello_classify.id as id,  wxxiaohello_classify.content as content ,count(wxxiaohello_blog.id) AS count FROM wxxiaohello_blog, wxxiaohello_classify where wxxiaohello_blog.classify_id = wxxiaohello_classify.id GROUP BY wxxiaohello_blog.classify_id ORDER BY wxxiaohello_classify.id asc"
        cursor.execute(raw_sql)
        fetchall = cursor.fetchall()    
        
        card=[]
        for obj in fetchall:
            dic={}
            dic['id']=(obj[0])
            dic['content']=str(obj[1].encode("utf8"))
            dic['count']=(obj[2])
            card.append(dic)
      #  return HttpResponse(jsondump.json_encode(filing_list.values()))
        return HttpResponse(jsondump.json_encode(card))